import java.util.ArrayList;

public class DBManipulator {

	// Constructor
	public DBManipulator() {

	}

	// Get null-free subschema
	public ArrayList<String> getNullFreeSubSchema(ArrayList<String[]> list,
			int col) {
		ArrayList<String> nfs = new ArrayList<String>();
		boolean[] flag = new boolean[col];

		for (int i = 0; i < col; i++) {
			flag[i] = true;
		}

		for (int i = 0; i < list.size(); i++) {
			for (int j = 0; j < col; j++) {
				if (flag[j]) {
					if (list.get(i)[j].equals("null")) {
						flag[j] = false;
					}
				}
			}
		}

		for (int i = 0; i < col; i++) {
			if (flag[i]) {
				nfs.add("col_" + (i + 1));
			}
		}

		return nfs;
	}

	// Set column names for the table
	public ArrayList<String> setAttribute(int col) {
		ArrayList<String> R = new ArrayList<String>();

		for (int i = 0; i < col; i++) {
			R.add("col_" + (i + 1));
		}

		return R;
	}

	public ArrayList<FuncDep> getFDs(ArrayList<String[]> table, int col) {
		ArrayList<FuncDep> FDs = new ArrayList<FuncDep>();

		// Check for FD for each column
		for (int i = 0; i < col; i++) {
			for (int j = 0; j < col; j++) {
				if (j != i) {
					ArrayList<String> left_list = new ArrayList<String>();
					ArrayList<String> right_list = new ArrayList<String>();
					boolean valid = true;

					for (int k = 0; k < table.size(); k++) {
						if (!table.get(k)[i].equals("null")) {
							String left = table.get(k)[i];
							int index = left_list.indexOf(left);

							if (index != -1) {
								String right = "null";

								if (!table.get(k)[j].equals("null")) {
									right = table.get(k)[j];
								}

								if (!right.equals(right_list.get(index))) {
									valid = false;
									break;
								}

							} else {
								left_list.add(table.get(k)[i]);
								if (!table.get(k)[j].equals("null")) {
									right_list.add(table.get(k)[j]);
								} else {
									right_list.add("null");
								}
							}
						}
					}

					if (valid) {
						FuncDep fd = new FuncDep("col_" + (i + 1), "col_"
								+ (j + 1));
						FDs.add(fd);
					}
				}
			}
		}

		return FDs;
	}
}
